package com.errol.batchprocessor.employeeaddition.advisorimpl.common;

import com.baomidou.mybatisplus.mapper.Condition;
import com.renjia.entity.CoreEmployee;
import com.renjia.entity.CoreEmployeeCustomer;
import com.renjia.enums.DocumentTypeEnum;
import com.renjia.enums.EmployeeAuthenticationStatusEnum;
import com.renjia.enums.EmployeeCustomerAuthStatusEnum;
import com.renjia.service.module.employeeaddition.advisorimpl.common.payload.AbstractEmployeeBatchPayload;
import com.renjia.service.module.employeeaddition.advisorimpl.common.payload.AbstractEmployeePiecePayload;
import com.renjia.service.module.employeeaddition.advisorimpl.common.payload.AbstractEmployeeSinglePayload;
import com.renjia.service.module.employeeaddition.advisorimpl.employee.payload.EmployeeListSinglePayload;
import org.apache.commons.lang3.StringUtils;
import org.springframework.lang.NonNull;

import java.util.List;

/**
 * @author zhang xiao bin
 * @version v1.0
 * @date 2021/03/25
 * @since v
 **/
public interface EmployeeIdentityInfoModifier<BE, SE, BP extends AbstractEmployeeBatchPayload<BE, SE>, PP extends AbstractEmployeePiecePayload<SE, SP>, SP extends AbstractEmployeeSinglePayload<SE>,
        IMPL extends AbstractEmployeeAdvisorImpl<BE, SE, BP, PP, SP>> {

    /**
     * 编辑人员信息
     * 编辑的功能设计比较乱，后面应该还需再改版，到时候重构
     *
     * @param singlePayload       sp
     * @param piecePayload        pp
     * @param batchPayload        bp
     * @param employeeAdvisorImpl 人员编辑实现
     * @return true 表示处理成功
     */
    default boolean doModifyEmployeeInfo(@NonNull SP singlePayload, @NonNull PP piecePayload, @NonNull BP batchPayload, @NonNull IMPL employeeAdvisorImpl) {
        // 编辑用户实名信息，sp.coreEmployee 是已存在的用户，由调用者负责查询
        if (singlePayload.getCoreEmployee() == null) {
            singlePayload.getErrMsgList().add("编辑的用户信息不存在");
            return false;
        }
        if (!employeeAdvisorImpl.checkMobileModifiable(singlePayload, batchPayload)) {
            // 修改手机号，且手机号被他人使用
            return false;
        }
        boolean nameModified = !singlePayload.getEmployeeName().equals(singlePayload.getCoreEmployee().getUserName());
        boolean bankCardModified = isBankCardModified(singlePayload);
        // 人员列表编辑地区紧急修复
        boolean addressModified = false;
        if (singlePayload.getClass() == EmployeeListSinglePayload.class) {
            if (!StringUtils.equals(singlePayload.getCoreEmployee().getRemark0(), ((EmployeeListSinglePayload) singlePayload).getSingleEntity().getAddress())) {
                addressModified = true;
                singlePayload.getCoreEmployee().setRemark0(((EmployeeListSinglePayload) singlePayload).getSingleEntity().getAddress());
            }
        }
        boolean identityAuthed = false;
        // 检查是否编辑证件信息
        if (!singlePayload.getDocumentTypeEnum().getCode().equals(singlePayload.getCoreEmployee().getDocumentType())
                || !singlePayload.getDocumentNumber().equals(singlePayload.getCoreEmployee().getDocumentNumber())) {
            // 更新证件信息，先检查检测新证件号是否被使用，未被使用时更新
            if (employeeAdvisorImpl.coreEmployeeMapper.selectCount(Condition.<CoreEmployee>wrapper()
                    .eq("document_type", singlePayload.getDocumentTypeEnum().getCode()).eq("document_number", singlePayload.getDocumentNumber())) > 0) {
                singlePayload.getErrMsgList().add("证件号码已被他人使用");
                return false;
            } else {
                // 证件号可以编辑，进行实名认证，并修改冗余信息
                if (!tryAuthIdentityAndUpdate(singlePayload, piecePayload, batchPayload, employeeAdvisorImpl)) {
                    // 实名失败
                    return false;
                } else {
                    identityAuthed = true;
                }
            }
        } else if (!EmployeeAuthenticationStatusEnum.AUTHENTICATED.getCode().equals(singlePayload.getCoreEmployee().getAuthIdentity())) {
            // 未编辑证件信息，但原用户实名未认证，需要实名认证
            if (!tryAuthIdentityAndUpdate(singlePayload, piecePayload, batchPayload, employeeAdvisorImpl)) {
                // 实名失败
                return false;
            } else {
                identityAuthed = true;
            }
        }
        if (bankCardModified && !identityAuthed) {
            // 银行卡修改，且未检查三要素，
            if (!tryAuthIdentityAndUpdate(singlePayload, piecePayload, batchPayload, employeeAdvisorImpl)) {
                return false;
            } else {
                identityAuthed = true;
            }
        }
        if (nameModified) {
            if (!identityAuthed && !tryAuthIdentityAndUpdate(singlePayload, piecePayload, batchPayload, employeeAdvisorImpl)) {
                return false;
            } else {
                identityAuthed = true;
            }
            // 姓名更新，更新银行卡关联的姓名
            employeeAdvisorImpl.coreUserBankMapper.updateUserNameByUserId(singlePayload.getEmployeeName(), singlePayload.getCoreEmployee().getId());
        }
        if (addressModified && !identityAuthed) {
            employeeAdvisorImpl.coreEmployeeMapper.updateById(singlePayload.getCoreEmployee());
        }
        if (singlePayload.isMobileModified() && !identityAuthed) {
            // 仅更新手机号
            employeeAdvisorImpl.coreEmployeeMapper.updateMobileById(singlePayload.getCoreEmployee().getId(), singlePayload.getMobile());
            employeeAdvisorImpl.coreEmployeeCustomerMapper.updateMobileByEmployeeId(singlePayload.getCoreEmployee().getId(), singlePayload.getMobile());
        }
        if (singlePayload.getClass() == EmployeeListSinglePayload.class && !identityAuthed) {
            if (singlePayload.getCoreEmployeeCustomer() == null) {
                singlePayload.setCoreEmployeeCustomer(employeeAdvisorImpl.coreEmployeeCustomerMapper.selectList(Condition.<CoreEmployeeCustomer>wrapper()
                        .eq("customer_id", batchPayload.getCoreCustomerChannelMerchant().getCustomerId())
                        .eq("channel_merchant_id", batchPayload.getCoreCustomerChannelMerchant().getChannelMerchantId())
                        .eq("employee_id", singlePayload.getCoreEmployee().getId())).get(0));
            }
            singlePayload.getCoreEmployeeCustomer().setRemark(((EmployeeListSinglePayload) singlePayload).getSingleEntity().getRemark());
            employeeAdvisorImpl.coreEmployeeCustomerMapper.updateById(singlePayload.getCoreEmployeeCustomer());
        }
        return true;
    }

    /**
     * 检查银行卡是否修改
     *
     * @param singlePayload sp
     * @return true 表示银行卡被编辑
     */
    boolean isBankCardModified(SP singlePayload);

    /**
     * 执行实名认证并更新冗余信息
     *
     * @param singlePayload       sp
     * @param piecePayload        pp
     * @param batchPayload        bp
     * @param employeeAdvisorImpl 人员编辑实现
     * @return true 表示处理成功
     */
    default boolean tryAuthIdentityAndUpdate(SP singlePayload, PP piecePayload, BP batchPayload, IMPL employeeAdvisorImpl) {
        if (batchPayload.isNeedCheckThreeElement() && !batchPayload.isShallForceAuthorized() && DocumentTypeEnum.ID == singlePayload.getDocumentTypeEnum()) {
            // 开启三要素校验、没有（多次失败后）强制三要素通过、而且是身份证，则进行三要素校验
            if (!employeeAdvisorImpl.isThreeElementSuccess(singlePayload, batchPayload)) {
                return false;
            }
        }
        singlePayload.getCoreEmployee().setUserName(singlePayload.getEmployeeName());
        singlePayload.getCoreEmployee().setDocumentType(singlePayload.getDocumentTypeEnum().getCode());
        singlePayload.getCoreEmployee().setDocumentNumber(singlePayload.getDocumentNumber());
        if (StringUtils.isEmpty(singlePayload.getCoreEmployee().getBankCard())) {
            singlePayload.getCoreEmployee().setBankCard(singlePayload.getBankCard());
        }
        // 实名已认证，ocr 状态不变
        employeeAdvisorImpl.employeeSupportService.renewalEmployeeOfAuthIdentity(singlePayload.getCoreEmployee());
        employeeAdvisorImpl.coreEmployeeMapper.updateById(singlePayload.getCoreEmployee());
        // 查找银行卡，或新建银行卡
        employeeAdvisorImpl.findUserBank(singlePayload, piecePayload, batchPayload);
        if (singlePayload.getCoreUserBank() == null) {
            singlePayload.setCoreUserBank(employeeAdvisorImpl.newUserBank(singlePayload, batchPayload));
            singlePayload.getCoreUserBank().setCreateAndUpdateUser(batchPayload.getCoreUser());
            employeeAdvisorImpl.coreUserBankMapper.insert(singlePayload.getCoreUserBank());
        }
        // 更新 employeeCustomer 实名冗余
        List<CoreEmployeeCustomer> coreEmployeeCustomers = employeeAdvisorImpl.coreEmployeeCustomerMapper.selectList(Condition
                .<CoreEmployeeCustomer>wrapper().eq("employee_id", singlePayload.getCoreEmployee().getId()));
        coreEmployeeCustomers.forEach(coreEmployeeCustomer -> {
            if (EmployeeCustomerAuthStatusEnum.UNAUTHORIZED.getCode().equals(coreEmployeeCustomer.getAuthIdentity())) {
                // 实名未认证的 employeeCustomer ，更新实名信息，及三项认证状态（通过 employee 的三项认证状态）
                employeeAdvisorImpl.employeeCustomerSupportService.renewalEmployeeCustomerOfIdentityInfo(coreEmployeeCustomer,
                        singlePayload.getEmployeeName(), singlePayload.getDocumentTypeEnum(), singlePayload.getDocumentNumber(), singlePayload.getCoreUserBank());
                employeeAdvisorImpl.employeeCustomerSupportService.renewalEmployeeCustomerOfAuthStatus(coreEmployeeCustomer,
                        singlePayload.getCoreEmployee(), batchPayload.getCoreCustomerChannelMerchant());
            } else {
                // 实名已认证的仅更新姓名和证件信息，除非银行卡号丢失
                if (StringUtils.isEmpty(coreEmployeeCustomer.getBankCard())) {
                    employeeAdvisorImpl.employeeCustomerSupportService.renewalEmployeeCustomerOfIdentityInfo(coreEmployeeCustomer,
                            singlePayload.getEmployeeName(), singlePayload.getDocumentTypeEnum(), singlePayload.getDocumentNumber(), singlePayload.getCoreUserBank());
                } else {
                    coreEmployeeCustomer.setEmployeeName(singlePayload.getEmployeeName());
                    coreEmployeeCustomer.setDocumentType(singlePayload.getDocumentTypeEnum().getCode());
                    coreEmployeeCustomer.setDocumentNumber(singlePayload.getDocumentNumber());
                }
            }
            if (singlePayload.getCoreEmployeeCustomer() == null
                    && batchPayload.getCoreCustomerChannelMerchant().getChannelMerchantId().equals(coreEmployeeCustomer.getChannelMerchantId())
                    && batchPayload.getCoreCustomerChannelMerchant().getCustomerId().equals(coreEmployeeCustomer.getCustomerId())) {
                singlePayload.setCoreEmployeeCustomer(coreEmployeeCustomer);
                employeeAdvisorImpl.employeeCustomerSupportService.renewalEmployeeCustomerOfIdentityInfo(coreEmployeeCustomer,
                        singlePayload.getEmployeeName(), singlePayload.getDocumentTypeEnum(), singlePayload.getDocumentNumber(), singlePayload.getCoreUserBank());
                if (singlePayload.getClass() == EmployeeListSinglePayload.class) {
                    singlePayload.getCoreEmployeeCustomer().setRemark(((EmployeeListSinglePayload) singlePayload).getSingleEntity().getRemark());
                }
            }
            if (StringUtils.isNotEmpty(singlePayload.getMobile())) {
                coreEmployeeCustomer.setRemark1(singlePayload.getMobile());
            }
            employeeAdvisorImpl.coreEmployeeCustomerMapper.updateById(coreEmployeeCustomer);
        });
        return true;
    }

}
